<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerBudgetModel;
use app\common\model\worker\CustomerGoodsDataModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\CustomerRulerModel;
use app\common\model\worker\RecommendActionLogModel;
use app\common\model\worker\RecommendAuthModel;
use app\common\model\worker\RecommendFollowLogModel;
use app\common\model\worker\RecommendModel;
use DateTime;
use think\facade\Db;
use think\Request;

class recommendController extends Base
{

    private $model;

    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->model = new RecommendModel();
    }

    /**
     * 列表
     * @return array|string
     * @throws \Exception
     */
    public function index()
    {
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $map = [];
        $searchData    = $this->getSearchData();
        $data          = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->where($map)->count();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)->page($pageNumber, $pageSize)
                ->where($map)->order($order)->select()->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
        }
        $this->result($data);
    }



    public function add(){
        $data = $this->request->param();
        $recommend_type = $data['recommend_type'] ?? 1;//新建分类 1设计师 2 异业
        if(!in_array($recommend_type,[1,2])){

            $this->result([],'新建分类不能为空',0);
        }
        $rule = [
            'recommend_type|新建分类' => 'require',
            'recommend_name|姓名'=>'require',
            'recommend_mobile|手机号码'=>'require|mobile',
            'recommend_birthday|生日'=>'require',
            'recommend_hobby|兴趣爱好'=>'require',
            'recommend_taboo|禁忌事项'=>'require',
            'province_id|省'=>'require',
            'city_id|市'=>'require',
            'area_id|区县'=>'require',
            'account_name|账户名称'=>'require',
            'account_number|账户号'=>'require',
            'bank_name|银行名称'=>'require',
            'open_bank|开户行'=>'require',
            'cate_id|推荐人分类'=>'require',
        ];
        if($recommend_type == 1){
            $rule['recommend_compay|公司名称'] = 'require';
            $rule['floor|楼牌号'] = 'require';
            $rule['address|小区'] = 'require';
        }elseif($recommend_type == 2){
            $rule['recommend_compay|品牌名称'] = 'require';
            $rule['floor|楼层'] = 'require';
        }
        $this->validate($data,$rule);
        $data['action_admin_id'] = $this->loginInfo['id'];
        // 启动事务
        $info = $this->model->add($data,$this->loginInfo['id']);

        if(!$info){
            $this->result([], "操作失败", 0);
        }

        $this->result($info,'操作成功',1);
    }


    public function edit(){
        $data = $this->request->param();
        $this->validate($data,[
            'recommend_name|姓名'=>'require',
            'recommend_mobile|手机号码'=>'require|mobile',
            'recommend_compay|公司名称'=>'require',
        ]);


        //todo 验证是否有编辑权限
        $data['action_admin_id'] = $this->loginInfo['id'];
        Db::startTrans();
        $info = $this->model->edit($data);
        if(!$info){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        $actionLog = [
            'recommend_id'=>$info['id'],
            'action_log'=>json_encode($info),//创建者
            'remark'=>'edit',
            'action_admin_id'=>$this->loginInfo['id'],//操作人di
        ];
        $result = RecommendActionLogModel::create($actionLog);
        if(!$result){
            // 回滚事务
            Db::rollback();
            $this->result([], "操作失败", 0);
        }
        Db::commit();
        $this->result($info,'操作成功',1);
    }


    public function info(){
        $Id = $this->request->param('id');
        $info = $this->model->getInfo(['id'=>$Id]);
        $this->result($info,'操作成功',1);
    }

    public function del(){
        $id = $this->request->param('id/d');
        $this->model->del($id);
        $this->result([],'操作成功',1);
    }

    public function list(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d',1); //当前页
        $recommend_type       = $this->request->param('recommend_type', '') ;//设计师1 异业2
        $cate_id       = $this->request->param('cate_id', '') ;
        $keyword = $this->request->param('keyword');
        $login_user_id = $this->request->param('login_user_id', '');
        $map = [];
        if($login_user_id){

        }
        if($recommend_type){
            $map[] = ['recommend_type', '=', $recommend_type];
        }


        if($cate_id){
            $map[] = ['cate_id', '=', $cate_id];
        }

        if (!empty($keyword)) {
            $map[] = ['recommend_name|recommend_mobile|recommend_hobby', 'like', '%' . $keyword . '%'];
        }

        $role_ids = $this->role_ids;
        $is_show = false;
        foreach ($role_ids as $v){
            if(in_array($v,[1,2,3,4])){
                $is_show = true;
            }
        }
        $myRecommendIds = RecommendAuthModel::where('admin_id',$this->loginInfo['id'])->where('role','create')->column('recommend_id');
        if(!$is_show){

            $map[] = ['id', 'in', $myRecommendIds];
        }


        $result  = $this->model->where('status',1)->where($map) ->field('id,recommend_compay,recommend_name as text,recommend_mobile')->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);

        foreach ($result as $v){
            $customer_ids = CustomerModel::where('recommend_id',$v->id)->column('id');//推荐人下的客户id
            $normal_customer_ids = CustomerModel::where('recommend_id',$v->id)->where('customer_status',1)->column('id');//推荐人推荐 已放弃的客户id
            $abandon_customer_ids = CustomerModel::where('recommend_id',$v->id)->where('customer_status',-1)->column('id');//推荐人推荐 已放弃的客户id
            $in_store_customer_ids = CustomerModel::where('recommend_id',$v->id)->where('customer_status',-1)->column('id');//进过店的客户id
            //最近一次得跟进记录
            $recommendFollowLogInfo = RecommendFollowLogModel::where('recommend_id',$v->id)->order('id','desc')->find();

            if($recommendFollowLogInfo){
                $date1 = new DateTime("now");

                $date2 = new DateTime($recommendFollowLogInfo['create_time']);

                $interval = $date2->diff($date1);
                $day_diff = $interval->days;

            }else{
                $recommendFollowLogInfo  = RecommendModel::where('id',$v->id)->find();
                $date1 = new DateTime("now");

                $date2 = new DateTime($recommendFollowLogInfo['create_time']);

                $interval = $date1->diff($date2);
                $day_diff = $interval->days;
            }
            $v->follow_content = $recommendFollowLogInfo['content'] ?? '';//距上次跟进的内容
            $v->reply_content = $recommendFollowLogInfo['reply_content'] ?? '';//结果
            $v->day_diff = $day_diff ?? '';//距上次跟进的天数
            $arr = ['week','month','year','all'];
            $data_detail = [];
            foreach($arr as $kk=>$vv){
                if($vv =='week'){
                    $data_detail[$kk] = [
                        'follow_meet' => RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type',1)->whereTime('create_time','week')->count() ?? 0,
                        'follow_other'=> RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type','<>',1)->whereTime('create_time','week')->count() ?? 0,
                        'budget_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('budget_id','<>',null)->group('customer_id')->whereTime('create_time','week')->count() ??0,
                        'budget_amount' => CustomerBudgetModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','week')->sum('budget_amount') ?? 0,
                        'ruler_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('ruler_id','<>',null )->group('customer_id')->whereTime('create_time','week')->count() ?? 0,
                        'ruler_amount' => CustomerRulerModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','week')->sum('budget_amount') ?? 0,
                        'in_store_nums' => CustomerModel::where('id','in',$in_store_customer_ids)->whereTime('create_time','week')->count() ?? 0,
                        'in_store_amount'=> CustomerBudgetModel::where('customer_id', 'in',$in_store_customer_ids)->whereTime('create_time','week')->sum('budget_amount') ?? 0,
                        'clinch_nums' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','week')->count() ?? 0,
                        'clinch_amount' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','week')->sum('payment_amount') ?? 0,
                        'abandon_nums' => CustomerModel::where('id','in',$abandon_customer_ids)->whereTime('create_time','week')->count() ?? 0,
                        'abandon_amount' => CustomerBudgetModel::where('customer_id','in',$abandon_customer_ids)->whereTime('create_time','week')->count() ??0,
                        'normal_nums' => CustomerModel::where('id','in',$normal_customer_ids)->whereTime('create_time','week')->count() ?? 0,
                        'normal_amount' =>  CustomerBudgetModel::where('customer_id','in',$normal_customer_ids)->whereTime('create_time','week')->count() ??0,

                    ];
                }elseif($vv == 'month'){

                    $data_detail[$kk] = [
                        'follow_meet' => RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type',1)->whereTime('create_time','month')->count() ?? 0,
                        'follow_other'=> RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type','<>',1)->whereTime('create_time','month')->count() ?? 0,
                        'budget_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('budget_id','<>',null)->group('customer_id')->whereTime('create_time','month')->count() ??0,
                        'budget_amount' => CustomerBudgetModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','month')->sum('budget_amount') ?? 0,
                        'ruler_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('ruler_id','<>',null )->group('customer_id')->whereTime('create_time','month')->count() ?? 0,
                        'ruler_amount' => CustomerRulerModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','month')->sum('budget_amount') ?? 0,
                        'in_store_nums' => CustomerModel::where('id','in',$in_store_customer_ids)->whereTime('create_time','month')->count() ?? 0,
                        'in_store_amount'=> CustomerBudgetModel::where('customer_id', 'in',$in_store_customer_ids)->whereTime('create_time','month')->sum('budget_amount') ?? 0,
                        'clinch_nums' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','month')->count() ?? 0,
                        'clinch_amount' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','month')->sum('payment_amount') ?? 0,
                        'abandon_nums' => CustomerModel::where('id','in',$abandon_customer_ids)->whereTime('create_time','month')->count() ?? 0,
                        'abandon_amount' => CustomerBudgetModel::where('customer_id','in',$abandon_customer_ids)->whereTime('create_time','month')->count() ??0,
                        'normal_nums' => CustomerModel::where('id','in',$normal_customer_ids)->whereTime('create_time','month')->count() ?? 0,
                        'normal_amount' =>  CustomerBudgetModel::where('customer_id','in',$normal_customer_ids)->whereTime('create_time','month')->count() ??0,
                    ];
                }elseif($vv == 'year'){
                    $data_detail[$kk]= [
                        'follow_meet' => RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type',1)->whereTime('create_time','year')->count() ?? 0,
                        'follow_other'=> RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type','<>',1)->whereTime('create_time','year')->count() ?? 0,
                        'budget_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('budget_id','<>',null)->group('customer_id')->whereTime('create_time','year')->count() ??0,
                        'budget_amount' => CustomerBudgetModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','year')->sum('budget_amount') ?? 0,
                        'ruler_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('ruler_id','<>',null )->group('customer_id')->whereTime('create_time','year')->count() ?? 0,
                        'ruler_amount' => CustomerRulerModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','year')->sum('budget_amount') ?? 0,
                        'in_store_nums' => CustomerModel::where('id','in',$in_store_customer_ids)->whereTime('create_time','year')->count() ?? 0,
                        'in_store_amount'=> CustomerBudgetModel::where('customer_id', 'in',$in_store_customer_ids)->whereTime('create_time','year')->sum('budget_amount') ?? 0,
                        'clinch_nums' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','year')->count() ?? 0,
                        'clinch_amount' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->whereTime('create_time','year')->sum('payment_amount') ?? 0,
                        'abandon_nums' => CustomerModel::where('id','in',$abandon_customer_ids)->whereTime('create_time','year')->count() ?? 0,
                        'abandon_amount' => CustomerBudgetModel::where('customer_id','in',$abandon_customer_ids)->whereTime('create_time','year')->count() ??0,
                        'normal_nums' => CustomerModel::where('id','in',$normal_customer_ids)->whereTime('create_time','year')->count() ?? 0,
                        'normal_amount' =>  CustomerBudgetModel::where('customer_id','in',$normal_customer_ids)->whereTime('create_time','year')->count() ??0,
                        ];
                }elseif($vv == 'all'){
                    $data_detail[$kk] = [
                        'follow_meet' => RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type',1)->count() ?? 0,
                        'follow_other'=> RecommendFollowLogModel::where('recommend_id',$v->id)->where('follow_type','<>',1)->count() ?? 0,
                        'budget_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('budget_id','<>',null)->group('customer_id')->count() ??0,
                        'budget_amount' => CustomerBudgetModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','week')->sum('budget_amount') ?? 0,
                        'ruler_nums' => CustomerGoodsDataModel::where('customer_id','in',$normal_customer_ids)->where('ruler_id','<>',null )->group('customer_id')->count() ?? 0,
                        'ruler_amount' => CustomerRulerModel::where('customer_id', 'in',$normal_customer_ids)->whereTime('create_time','week')->sum('budget_amount') ?? 0,
                        'in_store_nums' => CustomerModel::where('id','in',$in_store_customer_ids)->count() ?? 0,
                        'in_store_amount'=> CustomerBudgetModel::where('customer_id', 'in',$in_store_customer_ids)->sum('budget_amount') ?? 0,
                        'clinch_nums' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->count() ?? 0,
                        'clinch_amount' => CustomerModel::where('id','in',$normal_customer_ids)->where('payment_amount','>', 0)->sum('payment_amount') ?? 0,
                        'abandon_nums' => CustomerModel::where('id','in',$abandon_customer_ids)->whereTime('create_time','week')->count() ?? 0,
                        'abandon_amount' => CustomerBudgetModel::where('customer_id','in',$abandon_customer_ids)->count() ??0,
                        'normal_nums' => CustomerModel::where('id','in',$normal_customer_ids)->count() ?? 0,
                        'normal_amount' =>  CustomerBudgetModel::where('customer_id','in',$normal_customer_ids)->count() ??0,
                    ];
                }
            }
            $v->data_detail =$data_detail;

        }
        $new_list = $result->toArray();
        array_multisort(array_column($new_list['data'], 'day_diff'), SORT_DESC, $new_list['data']); //SORT_DESC降序，SORT_ASC升序
        $this->result($new_list,'操作成功',1);
    }

    //todo 客户操作日志
    public function recommendActionLogList(Request $request){

        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $recommend_id    = $this->request->param('recommend_id/d') ?? ''; //推荐人id
        $list = RecommendActionLogModel::alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')->where('cal.recommend_id',$recommend_id)
            ->field('cal.id,a.nickname,cal.create_time,cal.recommend_id')
             ->paginate(['list_rows'=> $pageSize, 'page' => $pageNumber]);
        $this->result($list,'操作成功',1);
    }
    //todo 获取客户操作信息
    public function getLogInfo(Request $request){
        $param = $request->param();
        //开始校验
        $this->validate($param,[
            'id|记录id'=>'require',
        ]);
        $id = $param['id'];
        $list = RecommendActionLogModel::alias('cal')
            ->leftJoin('admin a', 'a.id = cal.action_admin_id')
            ->where('cal.id',$id)
            ->field('a.nickname,cal.create_time,cal.recommend_id,cal.action_log')
            ->find();
        if($list){
            $list['action_log'] = json_decode($list['action_log']);
        }


        $this->result($list,'操作成功',1);
    }
    //根据推荐人id获取客户信息
    public function getCustomerByRecommendId(Request $request){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d') ?? 1; //当前页
        $recommend_id    = $this->request->param('recommend_id/d') ?? ''; //客户id
        $list = CustomerModel::where('recommend_id', $recommend_id)->field('name,mobile,province,city,dist,house_estate,address')->paginate($pageSize, false, ['page' =>$pageNumber ]);
        $this->result($list,'操作成功',1);
    }
    //显示红点数量
    public function showRedNums(Request $request)
    {
        $recommend_type       = $this->request->param('recommend_type', '') ;//设计师1 异业2


        $role_ids = $this->role_ids;
        $is_show = false;
        foreach ($role_ids as $v){
            if(in_array($v,[1,2,3,4])){
                $is_show = true;
            }
        }


        $query = [];
        $myRecommendIds = RecommendAuthModel::where('admin_id',$this->loginInfo['id'])->where('role','create')->column('recommend_id');
        if(!$is_show){

            $query[1][] = ['id', 'in', $myRecommendIds];
            $query[2][] = ['id', 'in', $myRecommendIds];
            $query[3][] = ['id', 'in', $myRecommendIds];
            $query[4][] = ['id', 'in', $myRecommendIds];
            $query[5][] = ['id', 'in', $myRecommendIds];
        }

        $query[1][] = ['recommend_type','=',$recommend_type];
        $query[1][] = ['cate_id','=',1];
        $query[2][] = ['recommend_type','=',$recommend_type];
        $query[2][] = ['cate_id','=',2];
        $query[3][] = ['recommend_type','=',$recommend_type];
        $query[3][] = ['cate_id','=',3];
        $query[4][] = ['recommend_type','=',$recommend_type];
        $query[4][] = ['cate_id','=',4];
        $query[5][] = ['recommend_type','=',$recommend_type];
        $query[5][] = ['cate_id','=',5];

        $data['total_01']  = $this->model->where($query[1])->count();
        $data['total_02']  = $this->model->where($query[2])->count();
        $data['total_03']  = $this->model->where($query[3])->count();
        $data['total_04']  = $this->model->where($query[4])->count();
        $data['total_05']  = $this->model->where($query[5])->count();
        $this->result($data,'操作成功',1);

    }

}